<?php

/**
 * login actions.
 *
 * @package    Redsea20
 * @subpackage login
 * @author     Your name here 
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class loginActions extends sfActions
{
    /**
     * Execute Logout Process
     *
     * @param sfWebrequest $request  A request object
     */
    public function executeLogout(sfWebrequest $request)
    {
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->getAttributeHolder()->remove('currentuser');
        $this->getUser()->getAttributeHolder()->clear();
        $this->getUser()->shutdown();
        $this->redirect('main/index');
    }
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
        if ( $request->getParameter('Email') != null && $request->getParameter('Password') != null )
        {
            $userDeail = Doctrine_Query::create()
                        ->select('l.id, l.entityid, l.password')
                        ->from('login l')
                        ->leftJoin('l.Entity r')
                        ->where('l.emailaddress=\''.$this->getRequestParameter('Email').'\'')
                        ->andwhere('l.password=\''.md5($this->getRequestParameter('Password')).'\'')
                        ->execute();

            if( $userDeail->count() == 1)
            {
                foreach($userDeail as $userInfo)
                {
                    //$this->getUser()->setFlash('msg', 'Login Successful.');
                    $this->getUser()->setAuthenticated(true);
                    $this->getUser()->setAttribute("logged", true);
                    $this->getUser()->setAttribute("currentuser", Entity::GetEntity($userInfo->getEntityid("id")));
                    //$this->getUser()->setAttribute("emailaddress", $userInfo->Entity["firstname"].' '.$userInfo->Entity["lastname"]);
                    //$this->getUser()->setAttribute("userid", $userInfo->getEntityid("id"));

                    // Forward to HOME PAGE
                    //$this->redirect('home/index');  // module + '/' + action (indexSuccess.php)
                    echo '1';
                }
                //echo $userDeail[0]->Entity["firstname"].' '.$userDeail[0]->Entity["lastname"];
            }
            else
            {
                //$this->getUser()->setFlash('message', 'Invalid Email/Password. Try Again!.');
                //$this->getRequest()->setError('emailaddress', 'Email address cannot be blank');
                //$this->redirect('main/index');  // module + '/' + action (indexSuccess.php)
                echo '0';
            }
        }
        else
        {
            //$this->getUser()->setFlash('message', 'Invalid Email/Password. Try Again!.');
            //$this->getRequest()->setError('emailaddress', 'Email address cannot be blank');
            //$this->redirect('main/index');  // module + '/' + action (indexSuccess.php)
            echo '0';
        }
        return sfView::NONE;

//      foreach($this->q as $item){
//        echo $item->getPassword();
//      }
  }

  public function  executeLogin()
  {
    sView::SUCCESS;
  }

  public function executePrepareLogin()
  {
    if($this->getRequest()->getMethid() != sfRequest::POST)
    {
        sView::SUCCESS;
    }
    else
    {
        $usr = $this->getRequestParameter('Email');
        $pwd  =  $this->getRequestParameter('password');

        //$pwd = md5($pwd);

        if($usr == "test" && $pwd == "test")
        {
            echo 'LOGIN SUCCESS';
        }
        else
        {

            echo 'LOGIN FAIL';
        }
    }
  }

  /**
   *
   * @param sfWebRequest $request 
   */
  public function executeNewAccount(sfWebRequest $request)
  {      
      $this->form = new EntityForm();
      if($this->getRequest()->isMethod('post'))
      {
          $userAccount = $request->getParameter('entity');
          
          $this->form->bind($userAccount, $request->getFiles('entity'));
          $vSchema = $this->form->getValidatorSchema();
          $this->errorSchema = new sfValidatorErrorSchema($vSchema);
          if($this->form->isValid())
          {
              if(Login::isValidEmailAddress($userAccount['emailaddress']))
              {          
                  // Updating the Doctrine Object (Entity) through EntityFarm Values
                  $this->form->updateObject();

                  /*
                   * User group is being defined through parameter value
                   * if it's empty this means it is general user
                   */
                  $userGroup = $this->getRequestParameter('ugroup');


                  if( isset ( $userGroup ) )
                  {
                      // Process url parameter value and set user type
                  }
                  else
                  {
                      $this->form->getObject()->setEntitytyperefid(Types::$ENT_TYPE['GENERAL_USER']);                      
                  }
                  
                  // Saving an Entity
                  $this->form->save();

                  Login::createNewAccount($this->form->getObject(), $userAccount['emailaddress'], md5( $userAccount['password'] ));

                  // Setting the message for template
                  //$this->getUser()->setFlash('message', 'User Created Successfully');
                  //$this->getUser()->setFlash('message', $this->form->getObject()->getPrimaryKey());

                  /*
                   * After registration user should be redirected to home page {Ref: Fahmi}
                   * Therefore setting User Session
                   */
                 $this->getUser()->setAuthenticated(true);
                 $this->getUser()->setAttribute("logged", true);
                 $this->getUser()->setAttribute("currentuser", $this->form->getObject());

                 // Forward to HOME PAGE
                 $this->redirect('home/index');
                  
                  // Returning blank form for new Entity Object
                  //$this->form = new EntityForm();
              }
              else
              {
                  $this->getUser()->setFlash('message', 'Email address already exists. Please use Forgot Password link to recover your password');
              }
          }
          else
          {
              // Form is not valid
              //echo $this->errorSchema->count();
              //
              // Setting the error message
              $this->getUser()->setFlash('message', 'Please correct the error(s) below');
              //echo 'VALIDATION FAILED';              
          }
      }

      return sfView::SUCCESS;

  }

  public function executeCancelRegistration(sfWebRequest $request)
  {
      $this->redirect('main/index');
  }

  public function executeResetPassword(sfWebRequest $request) {
      $emailAddress = $request->getParameter('email');

      if(isset ($emailAddress))
      {
          $passwordResetKey = Configurationtoken::generateToken($emailAddress, Types::$EMAIL_FORMAT['PASSWORD RESET']);
          $confirmResetUrl = 'http://'.$request->getHost().'/login/confirmPasswordReset?toc='. $passwordResetKey;
          $cancelResetUrl = 'http://'.$request->getHost().'/login/cancelPasswordReset?toc='.  $passwordResetKey;

          // Send a password reset email to the requested
           $emailSent = RBISUtility::sendEmail($emailAddress, 'RBIS PASSWORD RESET', sprintf( Emailformat::getEmailFormat(Types::$EMAIL_FORMAT['PASSWORD RESET']),$emailAddress, $confirmResetUrl, $cancelResetUrl), 0);

          echo $emailSent;
      }

      return sfView::NONE;
  }

  public function executeConfirmPasswordReset(sfWebRequest $request) {
      $tokenKey = $request->getParameter('toc');

      if($this->getRequest()->isMethod('post'))
      {
         $newPassword = $request->getParameter('txtNewPassword');
         $confirmPassword = $request->getParameter('txtConfirmPassword');
         $tk = $request->getParameter('hftk');
         
         if(isset ($newPassword) && isset ($confirmPassword) && $newPassword == $confirmPassword)
         {
             $token = Configurationtoken::getToken($tk, Types::$EMAIL_FORMAT['PASSWORD RESET']);

             // Redirect to error if no user in session
             $this->forward404Unless($token, sprintf('Invalid Request (%s).', ''));
             
             Login::resetPassword($token->getTokenvalue(), $newPassword);
             $this->getUser()->setFlash('message', 'Passowrd has been changed successfully.');
         }
         else
         {
             // Print Message For Password Mismatch
             $this->getUser()->setFlash('message', 'Password Mismatch');
         }
         //Login::resetPassword($emailAddress, $newPassword);
      }
      elseif(!isset ($tokenKey) || !Configurationtoken::isValidToken($tokenKey))
      {
          // IF TOKEN NOT FOUND THEN REDIRECT TO ERROR PAGE
         $this->getUser()->setFlash('message', 'Invalid Request. Please contact administrator');
      }
      else
      {
          $this->token = $tokenKey;
      }
      
      return sfView::SUCCESS;
  }

  public function executeCancelPasswordReset(sfWebRequest $request) {
      return sfView::NONE;

  }
}
